﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TfsCommitMonitor.Tfs;

namespace TfsCommitMonitor
{
	internal class TfsTreeView : TreeView
	{
		private Font BoldFont;
		private Font RegularFont;

		internal TfsTreeView()
		{
			BoldFont = new Font(Font, FontStyle.Bold);
			RegularFont = new Font(Font, FontStyle.Regular);
		}

		protected override void Dispose(bool disposing)
		{
			BoldFont.Dispose();
			BoldFont = null;
			RegularFont.Dispose();
			RegularFont = null;

			base.Dispose(disposing);
		}

		internal TreeNode CreateNode(Project project)
		{
			return
				new TreeNode(FormatNameAndUnreadCount(project.ProjectPath, project.UnreadCount)) 
				{ 
					NodeFont = GetNodeFont(project),
					Tag = project, 
				};
		}

		internal void UpdateNode(Project project)
		{
			var node = GetNodeByTag(Nodes, project);
			node.Text =
				FormatNameAndUnreadCount(project.ProjectPath, project.UnreadCount);
			node.NodeFont = GetNodeFont(project);
		}

		internal void RemoveNode(Project project)
		{
			var node = GetNodeByTag(Nodes, project);
			Nodes.Remove(node.Parent.Nodes.Count == 1 ? node.Parent : node);
			SelectedNode = null;
		}

		internal Project SelectedProject
		{
			get
			{
				return
					SelectedNode == null 
					?
					null
					:
					SelectedNode.Tag as Project;
			}
		}

		private static TreeNode GetNodeByTag(TreeNodeCollection nodes, Project project)
		{
			var foundNode =
				nodes
				.Cast<TreeNode>()
				.Where(node => node.Tag == project)
				.SingleOrDefault();

			if (foundNode != null)
				return foundNode;
			else
			{
				foreach (TreeNode node in nodes)
				{
					var foundSubNode = GetNodeByTag(node.Nodes, project);
					if (foundSubNode != null)
						return
							foundSubNode;
				}
			}

			return null;
		}

		private static String FormatNameAndUnreadCount(String name, Int32 unreadCount)
		{
			return
				String.Format("{0}{1}",
					name,
					unreadCount > 0 ? String.Format(" ({0})", unreadCount) : String.Empty);
		}

		private Font GetNodeFont(Project project)
		{
			return
				project.UnreadCount == 0
				?
				RegularFont
				:
				BoldFont;
		}
	}
}
